package com.athuiju.fenxiaoback.service.impl;

import com.athuiju.fenxiaoback.entity.TbCategory;
import com.athuiju.fenxiaoback.mapper.TbCategoryMapper;
import com.athuiju.fenxiaoback.service.TbCategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品类目表，类目和商品(spu)是一对多关系，类目与品牌是多对多关系 服务实现类
 * </p>
 *
 * @author athuiju
 * @since 2021-06-30
 */
@Service
public class TbCategoryServiceImpl extends ServiceImpl<TbCategoryMapper, TbCategory> implements TbCategoryService {

    @Override
    public List<TbCategory> queryAllCate() {

        QueryWrapper<TbCategory> wrapper = new QueryWrapper<TbCategory>();
        wrapper.orderByDesc("id");

        wrapper.select("id","name","parent_id","is_parent","sort","is_deleted","cimage");
        List<TbCategory> tbCategories = baseMapper.selectList(wrapper);


        System.out.println("---------------------" + tbCategories.size());
        List<TbCategory> resultCategories = buildTBCategory(tbCategories);
        System.out.println("---------------------" + resultCategories.size());
        return resultCategories;
    }

    private List<TbCategory> buildTBCategory(List<TbCategory> tbCategoriesList) {

        List<TbCategory> finalNode = new ArrayList<>();
        for (TbCategory categoryNode : tbCategoriesList) {
            if ("0".equals(categoryNode.getParentId().toString())) {
                categoryNode.setLevel(1);
                finalNode.add(selectChildren(categoryNode, tbCategoriesList));
            }
        }

        return finalNode;
    }


    private TbCategory selectChildren(TbCategory categoryNode, List<TbCategory> tbCategories) {
        System.out.println("selectChildren:tbCategories" + tbCategories.size());

        categoryNode.setChildren(new ArrayList<TbCategory>());


        for (TbCategory it : tbCategories) {

            if (categoryNode.getId().equals(it.getParentId().toString())) {

                int level = categoryNode.getLevel() + 1;
                it.setLevel(level);

                if (categoryNode.getChildren() == null) {
                    categoryNode.setChildren(new ArrayList<TbCategory>());
                }

                categoryNode.getChildren().add(selectChildren(it, tbCategories));
                if (categoryNode.getLevel() == 3) {
                    categoryNode.setChildren(null);
                }
                if (it.getLevel() == 3) {
                    it.setChildren(null);
                }
            }
        }
        return categoryNode;
    }

}
